﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting.Internal;
using Microsoft.Extensions.ObjectPool;
using Microsoft.IdentityModel.Tokens;
using MyAppAPI.Models;
using MyAppAPI.Models.Hotel;
using MyAppAPI.ParamModel;
using MyAppAPI.Services.interfaceService;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace MyAppAPI.Controllers
{
    [Route("api/")]
    [ApiController]
    public class HotelController : ControllerBase
    {
        private readonly IHotelService hotelService;
        private Microsoft.AspNetCore.Hosting.IHostingEnvironment environment;
        //延迟初始化
        private readonly JwtSettings jwtSettings;
        public HotelController(IHotelService _hotelService, Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment, JwtSettings _jwtSettings)
        {
            hotelService = _hotelService;
            environment = hostingEnvironment;
            jwtSettings = _jwtSettings;
        }
        [Route("Admin/Login")]
        [HttpGet]
        public async Task<ResultData<UserData>> HotelLogin(string loginId, string loginPwd)
        {
            var result = new ResultData<UserData>();
            var user = await hotelService.Login(loginId, loginPwd);
            if (user is null)
            {
                result.success = false;
                result.message = "登录失败";
                result.token = "123";
                return result;
            }

            result.success = true;
            result.message = "登录成功";
            //生成token
            {
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.NameIdentifier, user.loginId));
                claims.Add(new Claim(ClaimTypes.Name, user.name));
                var key = new SymmetricSecurityKey(jwtSettings.Key);
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    issuer: jwtSettings.Issuer,
                    audience: jwtSettings.Audience,
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(120),
                    signingCredentials: creds
                    );
                result.token = new JwtSecurityTokenHandler().WriteToken(token);
            }

            result.data = user;
            return result;
        }
        [Route("Admin/List")]
        [HttpGet]
        public UserInfosData GetAllUser(int roleId = 0, int pageIndex = 1, int pageSize = 10)
        {
            UserInfosData userInfosData = new();
            int count = 0;
            //组合model
            List<UserDetailData> userDetailDatas = new();
            var roleList = hotelService.GetAllRoleType().Result;
            if (roleId == 0)
            {
                var userDataList = hotelService.GetAllUser(ref count, pageIndex, pageSize);

                userDataList.ForEach(obj =>
                {
                    UserDetailData userDetailData = new();
                    userDetailData.roleId = obj.roleId;
                    userDetailData.id = obj.id;
                    userDetailData.name = obj.name;
                    userDetailData.loginId = obj.loginId;
                    userDetailData.loginPwd = obj.loginPwd;
                    userDetailData.phone = obj.phone;
                    userDetailData.photo = obj.photo;
                    userDetailData.role = roleList.Where(o => o.RoleId == obj.roleId).First();
                    userDetailDatas.Add(userDetailData);
                });
                userInfosData.data = userDetailDatas;
                userInfosData.count = count;
                userInfosData.pageIndex = pageIndex;
                userInfosData.pageSize = pageSize;
            }
            else
            {
                var userDataList = hotelService.GetAllUserByRoleId(roleId, ref count, pageIndex, pageSize);
                userDataList.ForEach(obj =>
                {
                    UserDetailData userDetailData = new();
                    userDetailData.roleId = obj.roleId;
                    userDetailData.id = obj.id;
                    userDetailData.name = obj.name;
                    userDetailData.loginId = obj.loginId;
                    userDetailData.loginPwd = obj.loginPwd;
                    userDetailData.phone = obj.phone;
                    userDetailData.photo = obj.photo;
                    userDetailData.role = roleList.Where(o => o.RoleId == obj.roleId).First();
                    userDetailDatas.Add(userDetailData);
                });
                userInfosData.data = userDetailDatas;// 
                userInfosData.count = count;
                userInfosData.pageIndex = pageIndex;
                userInfosData.pageSize = pageSize;
            }

            return userInfosData;
        }
        [Route("Admin/GetOne")]
        [HttpPost]
        public async Task<UserData> GetUser([FromBody] UserIdData userIdData)
        {
            return await hotelService.GetUser(userIdData.loginId);
        }
        [Route("Admin/Add")]
        [HttpPost]
        public async Task<ResultData<string>> AddUser([FromBody] UserData userData)
        {
            ResultData<string> resultData = new();
            bool insertSuccess = await hotelService.AddUser(userData);
            if (insertSuccess)
            {
                resultData.success = true;
                resultData.message = "添加成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "添加失败";
            }
            return resultData;
        }
        //[RequestSizeLimit(1_074_790_400)]
        [Route("Admin/UploadImg")]
        [HttpPost]
        public ResultData<string> UploadPicture(IFormFile file)
        {
            //List<IFormFile> files = new();
            //ResultData<string> resultData=new();
            //if(files.Count<1)
            //{
            //    resultData.success = false;
            //    resultData.message = "文件为空";
            //    return resultData;
            //}
            //List<string> filenames = new List<string>();
            //var now=DateTime.Now;
            //var filePath = string.Format("/Uploads/");
            //var webRootPath = environment.WebRootPath;
            //if(!Directory.Exists(webRootPath+filePath))
            //{
            //    Directory.CreateDirectory(webRootPath+filePath);
            //}
            //try
            //{
            //    foreach (var item in files)
            //    {
            //        if(item!=null)
            //        {
            //            var fileExtension = Path.GetExtension(item.FileName);
            //            const string fileFilt = ".gif|.jpg|.jpeg|.png";
            //            if(fileExtension==null)
            //            {
            //                break;
            //            }
            //            if(fileFilt.IndexOf(fileExtension.ToLower(),StringComparison.Ordinal)<-1)
            //            {
            //                break;
            //            }
            //            long length = item.Length;
            //            if(length>1024*1024*2)
            //            {
            //                break;
            //            }
            //            var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff");
            //            var strRan = Convert.ToString(new Random().Next(100, 999));
            //            var saveName = strDateTime + strRan + fileExtension;
            //            using (FileStream fs=System.IO.File.Create(webRootPath+filePath+saveName))
            //            {
            //                item.CopyTo(fs);
            //                fs.Flush();
            //            }
            //            filenames.Add(saveName);
            //        }
            //    }
            //    resultData.data = filenames.First();
            //    resultData.success= true;
            //    resultData.message = "上传成功";
            //}
            //catch (Exception ex)
            //{
            //    resultData.success = false;
            //    resultData.message = "上传失败"+ex.Message;
            //}
            //return resultData;
            ResultData<string> resultData = new();
            if (file == null)
            {
                resultData.success = false;
                resultData.message = "文件为空";
                return resultData;
            }
            var now = DateTime.Now;
            var filePath = string.Format("/Uploads/");
            var webRootPath = environment.WebRootPath;
            if (!Directory.Exists(webRootPath + filePath))
            {
                Directory.CreateDirectory(webRootPath + filePath);
            }
            try
            {
                var fileExtension = Path.GetExtension(file.FileName);
                const string fileFilt = ".gif|.jpg|.jpeg|.png";
                if (fileExtension == null)
                {
                    resultData.success = false;
                    resultData.message = "文件没有扩展标识符";
                    return resultData;
                }
                if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) < -1)
                {
                    resultData.success = false;
                    resultData.message = "未能标识文件类型";
                    return resultData;
                }
                long length = file.Length;
                if (length > 1024 * 1024 * 2)
                {
                    resultData.success = false;
                    resultData.message = "文件超出长度限制";
                    return resultData;
                }
                var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff");
                var strRan = Convert.ToString(new Random().Next(100, 999));
                var saveName = strDateTime + strRan + fileExtension;
                using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                resultData.success = true;
                resultData.message = "上传成功";
                resultData.data = saveName;
            }
            catch (Exception ex)
            {
                resultData.success = false;
                resultData.message = ex.Message;
                return resultData;
            }

            return resultData;
        }
        [Route("Admin/Update")]
        [HttpPost]
        public ResultData<string> UpdateUser([FromBody] UserData userData)
        {
            ResultData<string> resultData = new();
            bool updateSuccess = hotelService.UpdateUser(userData);
            if (updateSuccess)
            {
                resultData.success = true;
                resultData.message = "修改成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "修改失败";
            }
            return resultData;
        }
        [Route("Admin/Delete")]
        [HttpPost]
        public async Task<ResultData<string>> DeleteUser([FromBody] AdminDeleteData adminDeleteData)
        {
            ResultData<string> resultData = new();
            //先删数据库
            bool delSuccess = await hotelService.DeleteUser(adminDeleteData.id);

            //删本地图片
            if (delSuccess)
            {
                var filePath = string.Format("/Uploads/");
                var webRootPath = environment.WebRootPath;
                if (System.IO.File.Exists(webRootPath + filePath + adminDeleteData.photo))
                {
                    System.IO.File.Delete(webRootPath + filePath + adminDeleteData.photo);
                }
            }
            else
            {
                resultData.success = false;
                resultData.message = "删除失败";
                return resultData;
            }
            resultData.success = true;
            resultData.message = "删除成功";
            return resultData;
        }
        [Route("Admin/ResetPwd")]
        [HttpPost]
        public async Task<ResultData<string>> ResetPwd([FromBody] ResetPwdParams resetPwdParams)
        {
            ResultData<string> resultData = new();
            bool resetSuccess = await hotelService.ResetPwd(resetPwdParams);
            if (resetSuccess)
            {
                resultData.success = true;
                resultData.message = "修改密码成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "修改密码失败";
            }
            return resultData;
        }
        [Route("Role/List")]
        [HttpGet]
        public async Task<List<RoleData>> GetAllRoleType()
        {
            return await hotelService.GetAllRoleType();
        }
        [Route("Role/Add")]
        [HttpPost]
        public async Task<ResultData<string>> AddRoleType([FromBody] RoleNameData roleNameBody)
        {
            ResultData<string> resultData = new ResultData<string>();
            bool insertSuccess = await hotelService.AddRoleName(roleNameBody.roleName);
            resultData.data = string.Empty;
            if (insertSuccess)
            {
                resultData.success = true;
                resultData.message = "添加成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "添加失败";
            }
            return resultData;
        }
        [Route("Role/Delete")]
        [HttpPost]
        public async Task<ResultData<string>> DeleteRoleType([FromBody] RoleIdData roleIdBody)
        {
            ResultData<string> resultData = new ResultData<string>();
            bool deleteSuccess = await hotelService.DeleteRoleName(roleIdBody.roleId);
            resultData.data = string.Empty;
            if (deleteSuccess)
            {
                resultData.success = true;
                resultData.message = "删除成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "删除失败";
            }
            return resultData;
        }
        [Route("Role/GetOne")]
        [HttpPost]
        public async Task<RoleData> GetRoleByRoleId([FromBody] RoleIdData roleIdBody)
        {

            RoleData roleData = await hotelService.GetRoleByRoleId(roleIdBody.roleId);

            return roleData;
        }
        [Route("Role/Update")]
        [HttpPost]
        public ResultData<string> UpdateRoleByRoleId([FromBody] RoleData roleData)
        {
            ResultData<string> resultData = new ResultData<string>();
            bool updateSuccess = hotelService.UpdateRoleByRoleId(roleData);
            resultData.data = string.Empty;
            if (updateSuccess)
            {
                resultData.success = true;
                resultData.message = "修改成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "修改失败";
            }
            return resultData;
        }
        [Route("RoomType/List")]
        [HttpGet]
        public async Task<List<RoomTypeData>> GetAllRoomType()
        {
            return await hotelService.GetAllRoomType();
        }
        [Route("RoomType/Add")]
        [HttpPost]
        public async Task<ResultData<string>> AddRoomType([FromBody] RoomTypeData roomTypeBody)
        {
            ResultData<string> resultData = new ResultData<string>();
            bool insertSuccess = await hotelService.AddRoomType(roomTypeBody);
            resultData.data = string.Empty;
            if (insertSuccess)
            {
                resultData.success = true;
                resultData.message = "添加成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "添加失败";
            }
            return resultData;
        }
        [Route("RoomType/GetOne")]
        [HttpPost]
        public async Task<RoomTypeData> GetRoomTypeByRoomTypeId([FromBody] RoomTypeIdData roomTypeIdBody)
        {

            RoomTypeData roomTypeData = await hotelService.GetRoomTypeByRoomTypeId(roomTypeIdBody.roomTypeId);

            return roomTypeData;
        }
        [Route("RoomType/Update")]
        [HttpPost]
        public ResultData<string> UpdateRoomTypeByRoomTypeId([FromBody] RoomTypeData roleData)
        {
            ResultData<string> resultData = new ResultData<string>();
            bool updateSuccess = hotelService.UpdateRoomByRoomTypeId(roleData);
            resultData.data = string.Empty;
            if (updateSuccess)
            {
                resultData.success = true;
                resultData.message = "修改成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "修改失败";
            }
            return resultData;
        }
        [Route("RoomType/Delete")]
        [HttpPost]
        public async Task<ResultData<string>> DeleteRoomType([FromBody] RoomTypeIdData roomTypeIdBody)
        {
            ResultData<string> resultData = new ResultData<string>();
            bool deleteSuccess = await hotelService.DeleteRoomType(roomTypeIdBody.roomTypeId);
            resultData.data = string.Empty;
            if (deleteSuccess)
            {
                resultData.success = true;
                resultData.message = "删除成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "删除失败";
            }
            return resultData;
        }
        [Route("Room/List")]
        [HttpGet]
        public RoomDetailInfoData GetAllRoomDetailData(int roomTypeId = 0, int roomStateId = 0, int pageIndex = 1, int pageSize = 10,int guestId=0)
        {
            int count = 0;
            var roomDetailDatas = hotelService.GetAllRoomDetails(ref count, roomTypeId, roomStateId, pageIndex, pageSize, guestId);
            RoomDetailInfoData roomDetailInfoData = new();
            roomDetailInfoData.data = roomDetailDatas;
            roomDetailInfoData.count = count;
            roomDetailInfoData.pageIndex = pageIndex;
            roomDetailInfoData.pageSize = pageSize;
            return roomDetailInfoData;
        }
        [Route("RoomState/List")]
        [HttpGet]
        public List<RoomStateData> GetAllRoomState()
        {
            return hotelService.GetAllRoomState(0);
        }
        [Route("RoomState/ListToUpdate")]
        [HttpGet]
        public List<RoomStateData> GetPartRoomState()
        {
            return hotelService.GetAllRoomState(1);
        }
        [Route("Room/Add")]
        [HttpPost]
        public async Task<ResultData<string>> AddRoom([FromBody] RoomData roomBody)
        {
            ResultData<string> resultData = new ResultData<string>();
            bool insertSuccess = await hotelService.AddRoom(roomBody);
            resultData.data = string.Empty;
            if (insertSuccess)
            {
                resultData.success = true;
                resultData.message = "添加成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "添加失败";
            }
            return resultData;
        }
        [Route("Room/GetOne")]
        [HttpGet]
        public async Task<RoomData> GetRoomByRoomId(int roomId)
        {

            RoomData roomData = await hotelService.GetRoomByRoomId(roomId);

            return roomData;
        }
        [Route("Room/Update")]
        [HttpPost]
        public ResultData<string> UpdateRoomByRoomId([FromBody] RoomUpdateData roomUpdateData)
        {
            //id是原roomId
            ResultData<string> resultData = new ResultData<string>();
            RoomData roomData = new();
            bool flagSuccess = false;
            if (roomUpdateData.roomId == roomUpdateData.id)
            {
                //更新
                roomData = new() { roomId = roomUpdateData.roomId, description = roomUpdateData.description, roomTypeId = roomUpdateData.roomTypeId, roomStateId = roomUpdateData.roomStateId };
                flagSuccess = hotelService.UpdateRoomData(roomData);
            }
            else
            {
                var deleteSuccess = hotelService.DeleteRoomData(roomUpdateData.id);
                //进行删除，新增操作
                var newRoomData = new RoomData() { roomId = roomUpdateData.roomId, description = roomUpdateData.description, roomTypeId = roomUpdateData.roomTypeId, roomStateId = roomUpdateData.roomStateId };
                var addSuccess = hotelService.AddRoom(newRoomData).Result;
                if (deleteSuccess && addSuccess)
                {
                    flagSuccess = true;
                }
            }


            resultData.data = string.Empty;
            if (flagSuccess)
            {
                //其中id和roomid是为了方便更新成功之后写变更日志记录
                resultData.success = true;
                resultData.message = "修改成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "修改失败";
            }
            return resultData;
        }
        [Route("Room/Delete")]
        [HttpPost]
        public ResultData<string> DeleteRoomData([FromBody]RoomIdData roomIdData)
        {
            ResultData<string> resultData = new ResultData<string>();
            bool deleteSuccess = hotelService.DeleteRoomData(roomIdData.roomId);
            resultData.data = string.Empty;
            if (deleteSuccess)
            {
                resultData.success = true;
                resultData.message = "删除成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "删除失败";
            }
            return resultData;
        }
        [Route("GuestRecord/List")]
        [HttpPost]
        public GuestDetailInfoData GetAllGuestRecord([FromBody]GuestListRecordParam guestListRecordParam)
        {
            int count = 0;
            var guestData = hotelService.GetAllGuestRecord(ref count, guestListRecordParam.guestName, guestListRecordParam.resideStateId, guestListRecordParam.pageIndex, guestListRecordParam.pageSize);
            GuestDetailInfoData guestDetailInfoData = new();
            guestDetailInfoData.data = guestData;
            guestDetailInfoData.count = count;
            guestDetailInfoData.pageIndex = guestListRecordParam.pageIndex;
            guestDetailInfoData.pageSize = guestListRecordParam.pageSize;
            return guestDetailInfoData;
        }
        [Route("ResideState/List")]
        [HttpGet]
        public List<ResideState> GetAllResideStateData()
        {
            return hotelService.GetAllResideStateData();
        }
        [Route("ResideState/GetOne")]
        [HttpGet]
        public ResideState GetResideSatetByStateId(int resideStateId)
        {
            return hotelService.GetResideSatetByStateId(resideStateId);
        }
        [Route("GuestRecord/Add")]
        [HttpPost]
        public ResultData<string> AddGuestRecord([FromBody] GuestDataAddParam guestDataAddParam)
        {
            ResultData<string> resultData = new();
            var guestData = new GuestData() 
            { 
                guestName = guestDataAddParam.guestName,
                identityId=guestDataAddParam.identityId,
                phone=guestDataAddParam.phone,
                roomId=guestDataAddParam.roomId,
                resideDate=guestDataAddParam.resideDate.ToString("yyyy/MM/dd HH:mm:ss"),
                deposit=guestDataAddParam.deposit,
                guestNum=guestDataAddParam.guestNum,
                resideStateId=1
            };
            bool addSuccess=hotelService.AddGuestRecord(guestData);
            if(addSuccess)
            {
                resultData.success = true;
                resultData.message = "添加成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "添加失败";
            }
            return resultData;
        }
        [Route("GuestRecord/GetOne")]
        [HttpGet]
        public GuestReturnOneData GetGuestDataByGuestId(int guestId)
        {
            return hotelService.GetGuestDataByGuestId(guestId);
        }
        [Route("GuestRecord/Update")]
        [HttpPost]
        public ResultData<string> UpdateGuestData([FromBody] GuestDataAddParam guestDataUpdateParam)
        {
            ResultData<string> resultData = new();
            var guestData = new GuestData()
            {
                guestId= guestDataUpdateParam.guestId,
                guestName = guestDataUpdateParam.guestName,
                identityId = guestDataUpdateParam.identityId,
                phone = guestDataUpdateParam.phone,
                roomId = guestDataUpdateParam.roomId,
                resideDate = guestDataUpdateParam.resideDate.ToString("yyyy/MM/dd HH:mm:ss"),
                deposit = guestDataUpdateParam.deposit,
                guestNum = guestDataUpdateParam.guestNum,
                resideStateId = 1
            };
            bool updateSuccess=hotelService.UpdateGuestData(guestData);
            if(updateSuccess)
            {
                resultData.success = true;
                resultData.message = "更新成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "更新失败";
            }
            return resultData;
        }
        [Route("GuestRecord/Checkout")]
        [HttpPost]
        public GuestData GuestCheckout([FromBody]CheckoutParam checkoutParam)
        {
            GuestData guest = hotelService.Checkout(checkoutParam.guestId);
            return guest;
        }
        [Route("GuestRecord/Delete")]
        [HttpPost]
        public ResultData<string> DeleteGuestDataByGuestId([FromBody]GuestDeleteParam deleteParam)
        {
            ResultData<string> resultData = new();
            var deleteSuccess=hotelService.DeleteGuestDataByGuestId(deleteParam.guestId);
            if(deleteSuccess)
            {
                resultData.success = true;
                resultData.message = "删除成功";
            }
            else
            {
                resultData.success = false;
                resultData.message = "删除失败";
            }
            return resultData;
        }
        [Route("RoomType/TotalTypePrice")]
        [HttpGet]
        public List<RoomTypeTotalData> GetRoomTypeTotalMoney()
        {
            return hotelService.GetRoomTypeTotalMoney();
            //return new List<RoomTypeTotalData>();
        }
    }
}
